package com.emar.adx.yiqifa.java;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Created by xiaoliang
 * 2016/8/26 14:16
 *
 * @Version 1.0
 */
public class CodeImage {

    private static String LOGIN_CODE_KEY = "RandCheckCode";

    public void createVerCode(HttpServletRequest request,
                              HttpServletResponse response) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            // 指定生成的响应是图片
            response.setContentType("image/jpeg");
            int width = 150;
            int height = 36;
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB); // 创建BufferedImage类的对象
            Graphics g = image.getGraphics(); // 创建Graphics类的对象
            Graphics2D g2d = (Graphics2D) g; // 通过Graphics类的对象创建一个Graphics2D类的对象
            Random random = new Random(); // 实例化一个Random对象
            Font mFont = new Font("华文宋体", Font.BOLD, 30); // 通过Font构造字体
            g.setColor(getRandColor(200, 250)); // 改变图形的当前颜色为随机生成的颜色
            g.fillRect(0, 0, width, height); // 绘制一个填色矩形
            // 画一条折线
            BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
                    BasicStroke.JOIN_BEVEL); // 创建一个供画笔选择线条粗细的对象
            g2d.setStroke(bs); // 改变线条的粗细
            g.setColor(Color.DARK_GRAY); // 设置当前颜色为预定义颜色中的深灰色
            int[] xPoints = new int[6];
            int[] yPoints = new int[6];
            for (int j = 0; j < 6; j++) {
                xPoints[j] = random.nextInt(width - 1);
                yPoints[j] = random.nextInt(height - 1);
            }
            g.drawPolyline(xPoints, yPoints, 6);
            // 生成并输出随机的验证文字
            g.setFont(mFont);
            String sRand = "";
            int itmp = 0;
            for (int i = 0; i < 4; i++) {
                if (random.nextInt(2) == 1) {
                    itmp = random.nextInt(26) + 65; // 生成A~Z的字母
                } else {
                    itmp = random.nextInt(10) + 48; // 生成0~9的数字
                }
                char ctmp = (char) itmp;
                sRand += String.valueOf(ctmp);
                Color color = new Color(20 + random.nextInt(110),
                        20 + random.nextInt(110), 20 + random.nextInt(110));
                g.setColor(color);
                /** **随机缩放文字并将文字旋转指定角度* */
                // 将文字旋转指定角度
                Graphics2D g2d_word = (Graphics2D) g;
                AffineTransform trans = new AffineTransform();
                trans.rotate(random.nextInt(45) * 1.01 / 260, 15 * i + 10, 1);
                float scaleSize = random.nextFloat() + 0.8f;
                if (scaleSize > 1.1f)
                    scaleSize = 1f;
                trans.scale(scaleSize, scaleSize);
                g2d_word.setTransform(trans);
                /** ********************* */
                g.drawString(String.valueOf(ctmp), 30 * (i + 1), 30);

            }
            // 将生成的验证码保存到Session中
            HttpSession session = request.getSession(true);
            session.setAttribute(LOGIN_CODE_KEY, sRand.toLowerCase());
            g.dispose();
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Color getRandColor(int s, int e) {
        Random ran = new Random();
        if (s > 255)
            s = 255;
        if (e > 255)
            e = 255;
        int r = s + ran.nextInt(e - s);
        int g = s + ran.nextInt(e - s);
        int b = s + ran.nextInt(e - s);
        return new Color(r, g, b);
    }

    /**
     *
     * @Title: matchesString
     * @Description: 乱码解析
     * @param s
     * @return
     * @throws
     */
    public static String matchesString(String s) {
        String buffer = s;
        if (s != null && !"".equals(s.trim())) {
            String regex = ".*?[\\u4e00-\\u9fa5].*?";
            boolean flag = s.matches(regex);
            if (!flag) {
                // 首先使用转码的方式测试
                try {
                    String str = java.net.URLDecoder.decode(s, "UTF-8");
                    flag = str.matches(regex);
                    if (flag) {
                        return str;
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }

            int i = 0;
            // 处理浏览器发送的请求
            while (!flag && i < charsetArray.length) {
                try {
                    String newStr = new String(s.getBytes("ISO8859-1"),
                            charsetArray[i]);
                    if (i == 0) {
                        // 缓存第一次的请求
                        buffer = newStr;
                    }
                    i++;
                    flag = newStr.matches(regex);
                    if (flag) {
                        return newStr;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    private static String[] charsetArray = new String[] { "UTF-8", "GBK",
            "GB2312" };

}
